//app.js
import * as API_Member from './api/member'
import * as socketUtil from './api/socketUtil'
import request from './utils/request'
const config = require('./utils/config.js')
const QQMapWX = require('./utils/qqmap-wx-jssdk.min')
// var common = require('utils/common.js')
var service = require('utils/service.js')
var qqMapSdk;
App({
  // load: function (uri) {
  //   return require(uri)
  // },
  https: request,
  onLaunch: function () {
    let that = this
    // const token = wx.getStorageSync('token')
    that.removeToken().then(() => {
      // wx.clearStorageSync()

    })
    wx.removeStorageSync('token')
    //检查登录状态

    // that.login()
    // 检查过后检查缓存是否登陆过

    if (this.globalData.openId) {
      this.connectSocket(this.globalData.openId);
    } else {
      this.watch(this.connectSocket, "openId")
    }
    this.initSystmInfo();
    qqMapSdk = new QQMapWX({
      key: config.QQMapKey
    });
    this.globalData.qqMapSdk = qqMapSdk;
  },
  initSystmInfo: function () {
    let that = this;
    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        let statusBarHeight = res.statusBarHeight;//获取状态栏的高度
        //设置导航栏高度，判断不同系统，设置不同高度
        //导航文字区域高度px
        let navHeight = 44;
        if (res.platform == "ios") {
          navHeight = 44;
        } else if (res.platform == "android") {
          navHeight = 48;
        } else {
          navHeight = 44;
        }
        // 获取可使用窗口宽度

        let clientWidth = res.windowWidth;
        let windowHeight = res.windowHeight;

        // 算出比例 px单位转为rpx单位
        let ratio = 750 / clientWidth;

        //获取状态栏与导航栏高度的和
        //状态栏
        that.globalData.statusBarHeight = statusBarHeight * ratio;
        //导航栏
        that.globalData.navHeight = navHeight * ratio;
        that.globalData.navHeadHeight = that.globalData.statusBarHeight + that.globalData.navHeight;

        that.globalData.statusBarHeightpx = statusBarHeight;
        that.globalData.navHeightpx = navHeight;
        that.globalData.navHeadHeightpx = that.globalData.statusBarHeightpx + that.globalData.navHeightpx;
        that.globalData.ratio = ratio;
        that.globalData.clientWidth = clientWidth;
        that.globalData.windowHeight = windowHeight;
      }
    })

  },
  connectSocket: function (openid) {
    console.log("openid发生变化" + openid)
    if (!this.globalData.hasConnectSocket) {
      socketUtil.connect(openid);
      this.globalData.hasConnectSocket = true;
    } else {
      console.log("创建过了跳出")
    }

  },
  async login() {
    let that = this;
    if (this.globalData.getCodeReq) {
      while (this.globalData.getCodeReq) {
        const a = await this.asyTime(100);
        // console.info("等待")
      }
      // console.info("不用等待，直接返回")
      return
    }

    this.globalData.getCodeReq = true;
    const { code } = await wx.login({ timeout: 8000 })
    //进入就注册，如有openid直接用openid登录
    let openid = wx.getStorageSync('openid');
    //根据openid登录其它账号调试，调试后记得清除缓存否则无法回到自己的账号
    // openid="o-gWu5MDOdv21L8E3QVL94m1T_CI";
    const a = await API_Member.getOpenId(code, openid).then(res => {
      if (res.success) {
        console.log("tang");
        console.log(res)
        //that.globalData.openId = res.openId
        var openid = res.member.openId;
        wx.setStorageSync('openid', openid)
        wx.setStorageSync('token', res.token)
        wx.setStorageSync('member', res.member)
        that.globalData.isVip = res.member.isVip
        that.globalData.belowImageUrl = res.member.belowImageUrl
        that.globalData.openId = openid;
        that.globalData.getCodeReq = false;
        return
      }

    })

  },
  asyTime(time) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
      }, time)
    })
  },
  autoLogin() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    let that = this
    const openId = this.globalData.openId

    if (openId || openId == '暂无') {
      service.autoLogin(openId, (res) => {
        if (res.exist) {
          wx.setStorageSync('token', res.token)
          wx.setStorageSync('member', res.member)
          that.globalData.openId = res.member.openId
        }
        wx.hideLoading()
      }, (res) => {
        wx.hideLoading()
      })
    }

  },
  async removeToken() {

    service.removeToken(() => {
    }, (res) => { })

  },
  globalData: {
    userInfo: null,
    openId: '',
    systemInfo: wx.getSystemInfoSync(),
    // 首页跳转商品分类时第三方变量
    cityCode: '',
    // 纬度
    latitude: '',
    // 经度
    longitude: '',
    // 定位地址
    location: '',
    //状态栏高度
    statusBarHeight: 0,
    //导航栏高度
    navHeight: 0,
    //相乘比例
    ratio: 2,
    phone: false,
    toIndex: false,
    selectStoreId: 0,
    isVip: 'N',
    isLookVip: true // 不管是不是vip是否可以查看vip商品
  },
  watch: function (method, watchFiled) {

    //监听函数

    var obj = this.globalData;
    let value = '';
    Object.defineProperty(obj, watchFiled, {

      configurable: true,

      enumerable: true,

      set: function (newVal) {

        value = newVal;

        method(newVal);

      },

      get: function () {

        return value

      }

    })

  },
  onShow() {
    // this.refreshLocation()
  },
  refreshLocation() {
    return new Promise((resolve, reject) => {
      wx.showLoading()
      wx.getLocation({
        type: 'gcj02',
        success: (res) => {
          //纬度
          var latitude = res.latitude
          this.globalData.latitude = latitude
          //经度
          var longitude = res.longitude
          this.globalData.longitude = longitude
          resolve(res)
        },
        fail(res) {
          reject(res)
        },
        complete () {
          wx.hideLoading()
        }
      })
    })
  }
})
